$(function () {

    //学员,讲师地址生成二维码
    QRCodeInp();

    //初始化专业
    $.initSubject({
        element:'course-open-subject-box',//初始化专业select元素的ID
        context:'course-open-subject-context',//显示专业/科目名字内容ID
        initData:$('#subjectIds').val(),//初始化显示的专业数据，默认不设置
        removeCallback:function(parentId,subjectIds){//删除回调
            resetSubjectIds()
        },
        confirmCallback:function(parentId,subjectIds){//点击确认回调
            resetSubjectIds()
        }
    });

    /**
     * 重置专业ID串
     */
    function resetSubjectIds() {
        var _subjectIds = $.getAllSubjectIds("course-open-subject-context");
        $("input[name=subjectIds]").val(_subjectIds);
    }

    initLayerDate("#openTime",true);
    initLayerDate("#endTime",true);
    $("body").on('keyup','.data-num',function () {//监听提前进入时间、最大观看课程人数
        var num = $(this).val();
        if(!/^\d+$/.test(num)){
            $(this).val(0);
        }
    }).on('click','#newCreateLive',function () {//新建直播间
        var title = $("#title").val();
        newCreateLive(title,createLiveCallback);
    }).on("click","#newCreateLiveCC",function(){
        var liveBilling  = $('input[name="liveBilling"]:radio:checked').val();
        if( liveBilling==''||liveBilling==null||liveBilling==undefined){
            icModale(0, '请选择直播房间类型');
            return;
        }
        newCreateLiveCC(createLiveCallback,liveBilling)
    }).on('ifChanged','#replay',function (event) {//允许回放属性操作监听
        if (event.target.checked) {//勾选
            $("#replay").iCheck('check');
            $("input[name='replay']").val(2);
            $(".back-code").removeClass("hide");
        }else{//未勾选
            $(".back-code").addClass("hide");
            $("#replay").iCheck('uncheck');
            $("input[name='replay']").val(1);
        }
    }).on('click',".selectTeacher",function () {//选择讲师
        var subjectIds = $("input[name='subjectIds']").val();
        if(subjectIds==null || $.trim(subjectIds)==''){
            icModale(0, '请选择专业/科目');
            return;
        }
        var type = $(this).data('type');
        sTeacher(subjectIds,type);
    }).on('click','.deleteTeacher',function () {//删除讲师
        var type = $(this).data('type');
        deleteTeacher([type]);
    }).on('click','#courseOpenImageBtn',function () {//图片上传
        //初始化图片上传窗口
        initUpdateFileWin({
            fileType:'img',//文类类型["img","ico","xls","pdf","zip"]
            callback:'uploadCallback',
            cut:true,//开启剪切
            imgSize:DEFAULT_COURSE_IMG_SIZE,//剪切上传后生成图片的规格（开启剪切才起使用）
            aspectRatio:16/9//剪切区域的高宽比例（开启剪切才起使用）
        });
    }).on('click','#remove-image',function () {//删除封面
        removePageImg();
    }).on('click','#cancel',function () {//
        window.history.go(-1);
    }).on('click','#save-continue',function () {//保存，下一步
        saveCourseOpen(1);
    }).on('click','#save-back',function () {//保存，返回
        saveCourseOpen(2);
    }).on('click','.secondStep',function () {//保存，下一步
        saveCourseOpen(1);
    }).on("change","#backUrl",function(){
        var selected = $("#backUrl option:selected");
        var playUrl =  $(this).val().replace("http://","https://");
        $("#backCode").val(playUrl);
        var liveId =    selected.data('live');
        if(liveId==''||liveId==null){
            liveId=" ";
        }
        var playbackId =    selected.data('playback');
        if(playbackId==''||playbackId==null){
            playbackId=" ";
        }
        $("input[name='liveId']").val(liveId);
        $("input[name='playbackId']").val(playbackId);
        $("input[name='playBackType']").val("LIVE")
    }).on('click', '#uploadVideo', function () {//上传视频的时间
        popupWindows();
    }).on('click','#selectVideo',function () {//选择音频、视频
        selectCommonVideo("VIDEO");
    });

    /**
     * 保存
     * @param type 1保存，下一步，2保存，返回
     */
    function saveCourseOpen(type) {
        $(".save-btn-box").attr('disabled','disabled');
        var params = $("#courseOpen-form").serializeJSON();
        params = JSON.stringify(params);
        $.ajax({
            url:baseloaction +'/admin/course/open/saveCourseOpen',
            type:'post',
            dataType:'json',
            data:params,
            contentType:'application/json;charset=utf-8',
            success:function (result) {
                if(result.success==false){
                    $(".save-btn-box").removeAttr('disabled');
                    icModale(0,result.message);
                }else{
                    if(type==1){//下一步
                        var id = result.entity.id;
                        window.location.href = baseloaction +'/admin/course/open/initCourseOpenInfo?id='+id;
                    }else if(type==2){//返回
                        window.location.href = baseloaction +'/admin/course/open/courseOpenList';
                    }
                }
            },
            error:function (error) {
                $(".save-btn-box").removeAttr('disabled');
                icModale(0,'系统错误，免费直播基本信息保存失败');
            }
        });
    }

    /***
     * 删除讲师
     * @param list
     */
    function deleteTeacher(list) {
        $.each(list,function (index,type) {
            if(type==0){
                $("#tutor-Id").val(0);
                $("#teacher-Name").text(" 请选择授课讲师");
                $("#teacher-div span.deleteTeacher").addClass("hide");
            }
            if(type==1){
                $("#tutorOne-Id").val(0);
                $("#tutorOne-Name").text("请选择助教讲师");
                $("#tutorOne-div span.deleteTeacher").addClass("hide");
            }
            if(type==2){
                $("#tutorTwo-Id").val(0);
                $("#tutorTwo-Name").text("请选择助教讲师");
                $("#tutorTwo-div span.deleteTeacher").addClass("hide");
            }
        });
    }
    /**
     * 选择讲师
     * @param subjectIds
     * @param type
     */
    function sTeacher(subjectIds,type) {
        if(type==0){
            selectTeacher('radio',subjectIds,'selectTeacherCallback','1');
        }else if(type==1){
            selectTeacher('radio',subjectIds,'selectTeacherOneCallback','1');
        }else  if(type==2){
            selectTeacher('radio',subjectIds,'selectTeacherTwoCallback','1');
        }
    }

    function popupWindows() {
        var type = 1;
        var  message='请选择要上传的视频文件';

        index = parent.layer.open({
            type: 2,
            area: ['500px', '100px'],
            content: baseloaction +'/admin/liveToV/create/initVideoUploadPage?type='+type,
            shadeClose: false,
            shade: [0.3, '#000'],
            title: '<strong>'+message+'</strong>'
        });
        setMethods(callbackClose);
    }
//回调关闭上传素材资源时的公共弹窗
    callbackClose = function (){
        parent.layer.close(index);
    };
});
var close =null;
function setMethods (to){
    close =to;
};
/**
 * 选择授课讲师回调
 * @param data
 */
function selectTeacherCallback(data) {
    if (data!=null) {
        $("#teacher-div span.deleteTeacher").removeClass('hide');
        $("#teacher-div span#teacher-Name").text(data.teacherName);
        $("#teacher-Id").val(data.id);
    }
}
/**
 * 选择助教1讲师回调
 * @param data
 */
function selectTeacherOneCallback(data) {
    if (data!=null) {
        $("#tutorOne-div span.deleteTeacher").removeClass('hide');
        $("#tutorOne-div span#tutorOne-Name").text(data.teacherName);
        $("#tutorOne-Id").val(data.id);
    }
}
/**
 * 选择助教2讲师回调
 * @param data
 */
function selectTeacherTwoCallback(data) {
    if (data!=null) {
        $("#tutorTwo-div span.deleteTeacher").removeClass('hide');
        $("#tutorTwo-div span#tutorTwo-Name").text(data.teacherName);
        $("#tutorTwo-Id").val(data.id);
    }
}
/**
 * 图片上传回调
 * @param result
 */
function uploadCallback(result) {
    if(result!=null){
        $("input[name='imageJson']").val(encodeURIComponent(JSON.stringify(result)));
        $("#course-open-image").attr("src",result.pcUrlMap.large);
        $("#file-names").text(result.fileName);
        $("#create-time").text(result.createTime);
    }
}

/**
 * 直播创建回调
 * @param entity
 */
function createLiveCallback(entity) {
    $('#roomId').val(entity.room_id);
    /*$('input[name="liveBilling"]').val(entity.liveBilling);*/
    $('#teacherCode').val(entity.teacher_code);
    $('#adminCode').val(entity.admin_code);
    $('#studentCode').val(entity.student_code);
    $('#liveUrl').val(entity.sign);
    $('#pre-enter-time').val(entity.preEnterTime);
    $('#adminUrl').val(entity.adminUrl);
    $('#studentUrl').val(entity.studentUrl);
    $('#teacherUrl').val(entity.teacherUrl);
    var name = $('#title').val();
    if(name==null||name==''){
        $('#title').val(entity.title);
    }
    var openTime = $('#openTime').val();
    if(openTime==null||openTime==''){
        $('#openTime').val(entity.start_time);
    }
    var endTime = $('#endTime').val();
    if(endTime==null||endTime==''){
        $('#endTime').val(entity.end_time);
    }
    QRCodeInp();
}

//96k 资源上传回调
parent.window.addEventListener('message', function (response) {
    if (!$.isEmptyObject(response)) {
        $('input[name="backCode"]').val(response.data.msg);
        $("input[name='playBackType']").val("VIDEO")
        close();
    }
}, false);

/**
 * 选择回调
 * @param video
 */
function selectVideoCallback(video) {
    $("#backCode").val(video.code);
    $("input[name='playBackType']").val("VIDEO")
}

/**
 * 生成二维码
 * @constructor
 */
function QRCodeInp(){
    var teacherUrl = $('#teacherUrl').val();
    if(teacherUrl!=null && teacherUrl!=''){
        var qrcode = $('#teacherQRCodeInp').qrcode({render: "canvas", height: 140, width: 140, correctLevel: 2, text: teacherUrl}).find('canvas').hide();
        $("#teacherQRCodeInp").attr('src', qrcode[0].toDataURL());
    }

    var studentUrl = $('#studentUrl').val();
    if(studentUrl!=null && studentUrl!=''){
        var qrcode = $('#studentQRCodeInp').qrcode({render: "canvas", height: 140, width: 140, correctLevel: 2, text: studentUrl}).find('canvas').hide();
        $("#studentQRCodeInp").attr('src', qrcode[0].toDataURL());
    }

}
